<?php
/**
 * Класс проверки того, что сессия используется только одним пользователем.
 */
class Workset_Session_Validator_OneUser extends Zend_Session_Validator_Abstract
{
	const COOKIE_NAME = 'sidhash';

	/**
	 * @var array
	 */
	protected static $_aValidData = array();

	/**
	 * @return void
	 */
	public function setup()
	{
		switch (FALSE)
		{
			case count(self::$_aValidData):
				Zend_Session::isRegenerated() || Zend_Session::regenerateId();

			case isset($_COOKIE[self::COOKIE_NAME]):
			case isset(self::$_aValidData[$_COOKIE[self::COOKIE_NAME]]):
			case time() - self::$_aValidData[$_COOKIE[self::COOKIE_NAME]] < 3:
				while (!isset($sHash) || isset(self::$_aValidData[$sHash]))
				{
					$sHash = md5(microtime());
				}

				$aParams = session_get_cookie_params();
				setcookie(self::COOKIE_NAME,$sHash,$aParams['lifetime'],
					$aParams['path'],$aParams['domain'],$aParams['secure'],
					$aParams['httponly']);
				break;

			default:
				$sHash = $_COOKIE[self::COOKIE_NAME];
		}

		self::$_aValidData[$sHash] = time();
		$this->setValidData(self::$_aValidData);
	}

	/**
	 * @return bool
	 */
	public function validate()
	{
		$bResult = false;

		if (isset($_COOKIE[self::COOKIE_NAME]))
		{
			foreach ($this->getValidData() as $sHash => $iTime)
			{
				$bResult = ($sHash == $_COOKIE[self::COOKIE_NAME]) || $bResult;

				if ($bResult)
				{
					self::$_aValidData[$sHash] = $iTime;
				}
			}
		}

		return $bResult;
	}
}